<?php
class AdminController extends Zend_Controller_Action {
	
	public function init()
	{
		$message = '请登录';
	
		switch( $this->getRequest()->getActionName() ){ // TODO sortir les actions ci-dessous dans un controller "ouvert"
				
			case 'league':
			case 'modify-league':
			case 'save-league-team':
			case 'league-team':
				$access = false;
			    break;
			case 'login':
			case 'logout' :
			    $access = true;
			    break;   
		}
		if ( !$access ){
			$auth = Zend_Auth::getInstance();
			$auth->setStorage(new Zend_Auth_Storage_Session( 'Admin'));
			if ( $auth->hasIdentity() )
				$this->identity = $auth->getIdentity();
			else{
				$this->_redirect('/admin/login');
			}
		}
		
		$this->_helper->layout->setLayout('admin-layout');
	}
	
	public function loginAction() {
		
		$this->view->headScript()->appendFile ( '/js/jquery.js' );

		
		$form = $this->_manageFormLogin ();
		
		$this->view->formLogin = $form;
		
		$this->_helper->layout->setLayout('admin-login');
		
	}
	
	public function logoutAction()
	{
		Zend_Session::start(); //obligatoire pour que ça marche !
		//détruit les données de session coté serveur :
		Zend_Session::destroy();
		$this->_redirect('/');
	}
	
	public function leagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_league = new Model_League();
		$leagues = $model_league->getAllLeagues('desc');
		
		$this->view->leagues = $leagues;
	
		
		
	}
	

	public function newLeagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');

		$form = new Form_CreateLeague();
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
			
			if ($form->isValid( $this->_request->getPost() )) {
				$model_league = new Model_League();
				$league_id = $model_league->createNewLeague($this->_request->getPost('league_name'),
						                                    $this->_request->getPost('team_count'));
				$this->_redirect('/admin/league-team/league-id/' . $league_id);
				
			}
			
		}	
		
		$this->view->form = $form;
	    
	
	}
	
	public function leagueCloseAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			$model_league = new Model_League();
			$league = $model_league->closeLeagueById($league_id);
			$this->_redirect('/admin/league/');
				
		}
		
	}
	public function modifyLeagueAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			$model_league = new Model_League();
			$league = $model_league->getLeagueById($league_id);			
			$this->view->league = $league;
			
			
		}
	
	}
	
	public function saveLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			
			if($this->_request->isPost() ){
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
				
				$model_league_team = new Model_LeagueTeam();
				$count = 1;
				for($count=1;$count<$league->team_count +1;$count++){
					$model_league_team->modifyTeam($league_id,
							                    $count,
							                    $this->_request->getPost('team_'.$count), 
							                    $this->_request->getPost('user_'.$count),
												$this->_request->getPost('logo_'.$count));
				}
				
				
				$this->_redirect('/admin/league/');
			}else{
				
			}
			
				
				
		}
	
	}
	
	public function saveModifyLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
				
			if($this->_request->isPost() ){
				
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
	
				$model_league_team = new Model_LeagueTeam();
				$teams = $model_league_team->getTeamsByLeagueId($league_id);
				
				$model_game = new Model_Game();
				
				$count = 1;

				for($count=0;$count<$league->team_count;$count++){
					if(!empty($teams[$count]['username'])){ 
						if($teams[$count]['username']!=$this->_request->getPost('user_'.($count+1)) ||
							$teams[$count]['logo']!=$this->_request->getPost('logo_'.($count+1))	){						
							$model_game->clearGamesByLeagueIdAndTeamId($league_id,$teams[$count]['team_id']);
							$model_league_team->modifyTeam($league_id,
									$count+1,
									$this->_request->getPost('team_'.($count+1)),
									$this->_request->getPost('user_'.($count+1)),
									$this->_request->getPost('logo_'.($count+1)));							
						}
					}else{ 								
							$model_league_team->addTeam($league_id,
								$count+1,
								$this->_request->getPost('team_'.($count+1)),
								$this->_request->getPost('user_'.($count+1)),
								$this->_request->getPost('logo_'.($count+1)));
							$model_game->addGamesByLeagueIdAndTeamId($league_id,$count+1);
						
						
					}
					/*
					if( teamuser existe)
						 delete all games of this user
						 update team
						 add games
				    else 
						update team 
						add games*/
						 
							
					
				}
	
			
				$this->_redirect('/admin/league/');
			}else{
	
			}
				
	
	
		}
	
	}
	
	public function leagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
			
				$model_league = new Model_League();
				$league = $model_league->getLeagueById($league_id);
			   
				$model_league_team = new Model_LeagueTeam();
				$teams = $model_league_team->getTeamsByLeagueId($league_id);
			
			    $model_user = new Model_User();
			    $users = $model_user->getAllActiveUsers('asc');
			    
			    $all_active_user_ids = "";
			    $all_user_names = "";
				$this->view->league = $league;
				$this->view->teams = $teams;
			     foreach($users as $user){
			     	$all_active_user_ids .=''.$user->id .',';
			     
			     }
			     foreach($users as $user){
			     	$all_user_names .='"'.$user->username .'",';
			     
			     }
			     $all_user_ids = substr($all_user_ids,0,-1);
			     $all_user_names = substr($all_user_names,0,-1);
			     
			$this->view->all_active_user_ids = $all_active_user_ids;
			$this->view->all_user_names = $all_user_names;
			
				
		}
	
	}
	
	public function modifyLeagueTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league-id');
		if($league_id!=0){
				
			$model_league = new Model_League();
			$league = $model_league->getLeagueById($league_id);
	
			$model_league_team = new Model_LeagueTeam();
			$teams = $model_league_team->getTeamsByLeagueId($league_id);
				
			$model_user = new Model_User();
			$users = $model_user->getAllActiveUsers('asc');
			 
			$all_user_ids = "";
			$all_user_names = "";
			$this->view->league = $league;
			$this->view->teams = $teams;
			foreach($users as $user){
				$all_user_ids .=''.$user->id .',';
	
			}
			foreach($users as $user){
				$all_user_names .='"'.$user->username .'",';
	
			}
			$all_user_ids = substr($all_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
	
			$this->view->all_user_ids = $all_user_ids;
			$this->view->all_user_names = $all_user_names;
				
	
		}
	
	}
	
	public function deleteLeagueUserAction(){
		$league_id = (int)$this->_getParam('league-id');
		$team_id = (int)$this->_getParam('team-id');
		
		if($league_id!=0&&$team_id!=0){
			$model_league_team = new Model_LeagueTeam();
			
		    $model_league_team->deleteUserByLeagueIdAndTeamId($league_id,$team_id);
			$this->_redirect('/admin/league/');
		
		}
		
	}
	
	
	public function leagueScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league_id');
		
		$model_league_team = new Model_LeagueTeam();
		$model_league = new Model_League();
		if ($league_id==0){			
			$league_id = $model_league->getFirstLeagueId()->id;
			
		} 
		$leagues = $model_league_team->getLeagues();

		if($league_id!=0){
			$model_game = new Model_Game();
			//$games = $model_game->getAllGamesByLeagueId($league_id);
			$this->view->finished_games = $model_game->getFinishedGamesByLeagueId($league_id);
			$this->view->to_confirm_games = $model_game->getToConfirmGamesByLeagueId($league_id);
			$this->view->to_start_games = $model_game->getToStartGamesByLeagueId($league_id);
			$this->view->leagues = $leagues;
			$this->view->actuel_league_id = $league_id;
			$this->view->actuel_league_name = $model_league->getLeagueById($league_id)->name;	
		}else{
			
		}
	
	
	}
	
	
	public function inputScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$game_id = (int)$this->_getParam('game-id');
	
		if($game_id!=0){
	
			if($this->_request->isPost() ){
				$model_game = new Model_Game();
				$model_game->updateGameScoreByAdminUser($game_id,
						$this->_request->getPost('away_team_score'),
						$this->_request->getPost('home_team_score')     );
				$this->_redirect('/admin/league-score/league_id/'.$model_game->getGameById($game_id)->league_id);
			}else{
	
			}
	
	
	
		}
	}
	
	
	public function leagueSummaryAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$league_id = (int)$this->_getParam('league_id');
		$model_league_team = new Model_LeagueTeam();
		$model_league = new Model_League();
		if ($league_id==0){
			$league_id = $model_league->getFirstLeagueId()->id;
	
		}
		$leagues = $model_league_team->getLeagues();
	
		if($league_id!=0){
			
			$league = $model_league->getLeagueById($league_id);
				
			$model_game = new Model_Game();
			$games = $model_game->getAllGamesByLeagueId($league_id);
				
			$team_count = $league->team_count;
			$detail_teams ="";
			/* for the sorting */
			$teams = array();
			$teams_diff = array();
			$teams_got = array();
			$teams_ids = array();
			
			for($nb=1;$nb<$team_count+1;$nb++){
				$detail['team_name'] = $model_league_team->getLeagueTeamInfoByLeagueIdAndTeamId($league_id,$nb)->team_name;
				$detail['logo'] = $model_league_team->getLeagueTeamInfoByLeagueIdAndTeamId($league_id,$nb)->logo;
				$detail['match'] = 0;
				$detail['score'] = 0;
				$detail['win'] = 0;
				$detail['tie'] = 0;
				$detail['lose'] = 0;
				$detail['got'] = 0;
				$detail['lost'] = 0;
				$detail['diff'] = 0;
				$detail_teams[$nb] = $detail;
				$teams[$nb] = 0;
				$teams_diff[$nb] = 0;
				$teams_got[$nb] = 0;
				$teams_ids[$nb] = $nb;				
			}
				
			foreach($games as $game){
				if($game->home_team_confirm=='yes' && $game->away_team_confirm=='yes'){
					$detail_teams[$game->home_team_id]['match']++;
					$detail_teams[$game->away_team_id]['match']++;
					if($game->home_team_score>$game->away_team_score){
						$detail_teams[$game->home_team_id]['score'] += 3;
						$detail_teams[$game->home_team_id]['win']++;
						$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
						$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
						$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
							
						$detail_teams[$game->away_team_id]['lose']++;
						$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
						$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
						$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
							
						$teams[$game->home_team_id] +=3;
						$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
						$teams_got[$game->home_team_id] += $game->home_team_score;
						$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
						$teams_got[$game->away_team_id] += $game->away_team_score;
						
					}else if($game->home_team_score==$game->away_team_score){
						$detail_teams[$game->home_team_id]['score'] ++;
						$detail_teams[$game->home_team_id]['tie']++;
						$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
						$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
						$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
	
						$detail_teams[$game->away_team_id]['score'] ++;
						$detail_teams[$game->away_team_id]['tie']++;
						$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
						$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
						$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
	
						$teams[$game->home_team_id] ++;
						$teams[$game->away_team_id] ++;
						$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
						$teams_got[$game->home_team_id] += $game->home_team_score;
						$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
						$teams_got[$game->away_team_id] += $game->away_team_score;
						
					}else if($game->home_team_score<$game->away_team_score){
						$detail_teams[$game->home_team_id]['lose']++;
						$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
						$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
						$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
							
						$detail_teams[$game->away_team_id]['score'] += 3;
						$detail_teams[$game->away_team_id]['win']++;
						$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
						$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
						$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
							
						$teams[$game->away_team_id] +=3;
						$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
						$teams_got[$game->home_team_id] += $game->home_team_score;
						$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
						$teams_got[$game->away_team_id] += $game->away_team_score;
					}
				}
					
			}
			
			//arsort($teams);
			array_multisort($teams,SORT_DESC,SORT_NUMERIC ,$teams_diff,SORT_DESC,SORT_NUMERIC ,$teams_got,SORT_DESC,SORT_NUMERIC ,$teams_ids );

			
			foreach ($teams_ids as $id ){
				$detail_teams_dup[] = $detail_teams[$id];
			}
			$this->view->leagues = $leagues;
			$this->view->detail_teams = $detail_teams_dup;
			$this->view->actuel_league_name = $model_league->getLeagueById($league_id)->name;
			$this->view->actuel_league_id = $league_id;
		}
	}
	
	
	
	/////////////////////////////////////////////cup part
	
	public function cupAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_league = new Model_Cup();
		$cups = $model_league->getAllCups('desc');
		
		$this->view->cups = $cups;
		
		
	}
	
	public function newCupAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$form = new Form_CreateCup();
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
			
			if ($form->isValid( $this->_request->getPost() )) {
				$model_cup = new Model_Cup();
				$cup_id = $model_cup->createNewCup($this->_request->getPost('cup_name'),
						                           $this->_request->getPost('group_count'));
				$this->_redirect('/admin/cup-group/cup-id/' . $cup_id);
	
			}
				
		}
	
		$this->view->form = $form;
		 
	
	}
	
	public function cupCloseAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
			$model_cup = new Model_Cup();
			$league = $model_cup->closeCupById($cup_id);
			$this->_redirect('/admin/cup/');
	
		}
	
	}
	
	public function cupGroupAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
			$model_cup = new Model_Cup();
			$cup = $model_cup->getCupById($cup_id);
			
			$model_cup_team = new Model_CupTeam();
			
			if($this->_request->isPost() ){
				$groups = array('A','B','C','D',
						'E','F','G','H',
						'I','J','K','L',
						'M','N','O','P');
				
				
				$count = 0;
				$team_count = 0;
				while($count< $cup->group_count){
					$temp = 0;
					while($temp < $this->_request->getPost('group_' . ($count+1))){
						
						$model_cup_team->addTeam($cup->id, $team_count +1, $groups[$count], '', null);
						$team_count++;
						$temp++;
					}
					$count++;
				}	
				
				$model_cup->setTeamCount($cup->id,$team_count);
				$this->_redirect('/admin/cup-team/cup-id/' . $cup->id);
			}
			
			$this->view->cup = $cup;
			
		}
	
	}
	
	public function cupTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
				
			$model_cup = new Model_Cup();
			$cup = $model_cup->getCupById($cup_id);
	
			$model_cup_team = new Model_CupTeam();
			$teams = $model_cup_team->getTeamsByCupId($cup_id);
				
			$grouped_teams = "";
		    foreach($teams as $team){
		    	$grouped_teams[$team['group_name']][] = $team;
		    }			
			$model_user = new Model_User();
			$users = $model_user->getAllActiveUsers('asc');
			$cup_teams =  $model_cup_team->getActiveTeamsByCupId($cup_id);
			
			/*
			$model_cup_ko_game = new Model_CupKoGame();
			$ko_all_teams = $model_cup_ko_game->getGamesByCupId($cup_id);
			$ko_teams = "";
			foreach ($ko_all_teams as $ko_team){
				if(isset($ko_teams[$ko_team['node_id']])){
					
				}else{
					$ko_teams[$ko_team['node_id']]['home_team_name'] = $ko_team['home_team_name'];
					$ko_teams[$ko_team['node_id']]['away_team_name'] = $ko_team['away_team_name'];
				}
			}
			*/
			$all_active_user_ids = "";
			$all_user_names = "";
			$all_cup_team_ids = "";
			$all_cup_team_names ="";
			
			$this->view->cup = $cup;
			$this->view->teams = $grouped_teams;
		/*	$this->view->ko_teams = $ko_teams; */
			
			foreach($users as $user){
				$all_active_user_ids .=''.$user->id .',';
	
			}
			foreach($users as $user){
				$all_user_names .='"'.$user->username .'",';
	
			}
			
			foreach($cup_teams as $team){
				$all_cup_team_ids .=''.$team['team_id'] .',';
			
			}
			foreach($cup_teams as $team){
				$all_cup_team_names .='"'.$team['team_name'] .'",';
			
			}
			
			$all_active_user_ids = substr($all_active_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
			$all_cup_team_ids = substr($all_cup_team_ids,0,-1);
			$all_cup_team_names = substr($all_cup_team_names,0,-1);

			$this->view->all_active_user_ids = $all_active_user_ids;
			$this->view->all_user_names = $all_user_names;
			$this->view->all_cup_team_ids = $all_cup_team_ids;
			$this->view->all_cup_team_names = $all_cup_team_names;
				

		}
	
	}
	
	public function saveCupTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
			$model_cup = new Model_Cup();
			$cup = $model_cup->getCupById($cup_id);
			
			if($this->_request->isPost() ){
				if($this->_request->getPost('cible')=='group-stage'){			
					$model_cup_team = new Model_CupTeam();
					$count = 1;
					for($count=1;$count<$cup->team_count +1;$count++){
						$model_cup_team->modifyTeam($cup_id,
								$count,
								$this->_request->getPost('team_'.$count),
								$this->_request->getPost('user_'.$count),
								$this->_request->getPost('logo_'.$count));
					}
				}else if ($this->_request->getPost('cible')=='knock-out-stage'){
					$model_ko_games = new Model_CupKoGame();
				   $team_numbers = $cup->group_count *2 ;
					$round = 1;
					$count = 1;
					while( $team_numbers!=1){
 						for($i=0;$i<floor($team_numbers/2);$i++){
 							
 							$model_ko_games->modifyGame($cup_id,$count,$round,
 									                    $this->_request->getPost('ko_user_away_'.$count),
 														$this->_request->getPost('ko_user_home_'.$count));
							$count++;							
						}
						$team_numbers = ceil($team_numbers/2);
						$round++;
					}
				}

				$this->_redirect('/admin/cup/');
			}else{
	
			}	
		}
	
	}
	
	public function deleteCupUserAction(){
		$cup_id = (int)$this->_getParam('cup-id');
		$team_id = (int)$this->_getParam('team-id');
	
		if($cup_id!=0&&$team_id!=0){
			$model_cup_team = new Model_CupTeam();
				
			$model_cup_team->deleteUserByCupIdAndTeamId($cup_id,$team_id);
			$this->_redirect('/admin/cup/');
	
		}
	
	}
	
	public function cupSummaryAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup_id');
		$model_cup_team = new Model_CupTeam();
		$model_cup = new Model_Cup();
		if ($cup_id==0){
			$cup_id = $model_cup->getFirstCupId()->id;
	
		}
		$cups = $model_cup_team->getCups();

		if($cup_id!=0){
				
			$cup = $model_cup->getCupById($cup_id);
	
			$model_cup_game = new Model_CupGame();
			
			$groups = $model_cup_team->getGroupsByCupId($cup_id);
			
			$details = "";			
			foreach($groups as $group){	
                $num = $model_cup_team->getTeamCountByCupIdAndGroupName($cup_id,$group['group_name']);
				$details[$group['group_name']] = $this->sortCupGames($model_cup_game->getGamesByCupIdAndGroupId($cup_id,$group['group_name']),
						                                             $num['num'], $model_cup_team, $cup_id,$group['group_name']);
			}
			
			
			$this->view->cups = $cups;
			$this->view->detail_teams = $details;
			$this->view->actuel_cup_name = $cup->name;
			$this->view->actuel_cup_id = $cup_id;
		}    
	}
	
	public function cupScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	   
		$cup_id = (int)$this->_getParam('cup_id');
	
		$model_cup_team = new Model_CupTeam();
		$model_cup= new Model_Cup();
		if ($cup_id==0){
			$cup_id = $model_cup->getFirstCupId()->id;
				
		}
		$cups = $model_cup_team->getCups();
	
		if($cup_id!=0){
			$groups = array('A','B','C','D',
					'E','F','G','H',
					'I','J','K','L',
					'M','N','O','P');
			
			$model_cup_game = new Model_CupGame();
			$cup = $model_cup->getCupById($cup_id);
			$group_count = $cup->group_count;
			for($i=0; $i<$group_count;$i++){
				$finished_games[$groups[$i]] =  $model_cup_game->getFinishedGamesByCupId($cup_id,$groups[$i]);
				$to_confirm_games[$groups[$i]] = $model_cup_game->getToConfirmGamesByCupId($cup_id,$groups[$i]);
				$to_start_games[$groups[$i]] = $model_cup_game->getToStartGamesByCupId($cup_id,$groups[$i]);
			}
			
			
			
			$this->view->finished_games = $finished_games;
			$this->view->to_confirm_games = $to_confirm_games;
			$this->view->to_start_games = $to_start_games;
			$this->view->cups = $cups;
			$this->view->actuel_cup_id = $cup_id;
			$this->view->actuel_cup_name = $cup->name;
		}else{
				
		}
	
	
	}
	
	
	public function cupInputScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$game_id = (int)$this->_getParam('game-id');
	
		if($game_id!=0){
	
			if($this->_request->isPost() ){
				$model_game = new Model_CupGame();
				$model_game->updateGameScoreByAdminUser($game_id,
						$this->_request->getPost('away_team_score'),
						$this->_request->getPost('home_team_score')     );
				$this->_redirect('/admin/cup-score/cup_id/'.$model_game->getGameById($game_id)->cup_id);
			}else{
	
			}
	
	
	
		}
	}
	
	
	/////////////////////////////////////cup ko part
	
	public function cupKoAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$model_cup_ko = new Model_CupKo();
		$cups = $model_cup_ko->getAllCups('desc');
	
		$this->view->cups = $cups;
	
	
	}
	
	
	public function newCupKoAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$form = new Form_CreateCupKo();
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
				
			if ($form->isValid( $this->_request->getPost() )) {
				$model_cup_ko = new Model_CupKo();
				$cup_id = $model_cup_ko->createNewCup($this->_request->getPost('cup_name'),
						$this->_request->getPost('team_count'),
						$this->_request->getPost('type'));
				
				$model_cup_ko_game = new Model_CupKoGame();
				$model_cup_ko_game->generateAllGames($cup_id,$this->_request->getPost('team_count'),$this->_request->getPost('type'));
				$this->_redirect('/admin/cup-ko-team/cup-id/' . $cup_id);
	
			}
	
		}
	
		$this->view->form = $form;
			
	
	}
	
	public function cupKoTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
				
			$model_cup_ko = new Model_CupKo();
			$cup = $model_cup_ko->getCupKoById($cup_id);

			$model_cup_ko_team = new Model_CupKoTeam();
			$teams = $model_cup_ko_team->getTeamsByCupKoId($cup_id);
				
			$model_user = new Model_User();
			$users = $model_user->getAllActiveUsers('asc');
			 
			$all_active_user_ids = "";
			$all_user_names = "";
			$this->view->cup = $cup;
			$this->view->teams = $teams;
			foreach($users as $user){
				$all_active_user_ids .=''.$user->id .',';
	
			}
			foreach($users as $user){
				$all_user_names .='"'.$user->username .'",';
	
			}
			$all_user_ids = substr($all_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
	
			$this->view->all_active_user_ids = $all_active_user_ids;
			$this->view->all_user_names = $all_user_names;
				
	
		}
	
	}
	
	public function saveCupKoTeamAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
				
			if($this->_request->isPost() ){
				$model_cup_ko = new Model_CupKo();
				$cup = $model_cup_ko->getCupKoById($cup_id);
	
				$model_cup_ko_team = new Model_CupKoTeam();
				$teams = $model_cup_ko_team->getTeamsByCupKoId($cup_id);
				
				for($count=0;$count<$cup->team_count ;$count++){	
					
					if(!empty($teams[$count]['username'])){
						
						if($teams[$count]['username']!=$this->_request->getPost('user_'.($count + 1))){
							
							$model_cup_ko_team->modifyTeam($cup_id,
							$count+1,
							$this->_request->getPost('team_'.$count+1),
							$this->_request->getPost('user_'.$count+1));
						}
					}else{
						$model_cup_ko_team->addTeam($cup_id,
								$count +1,
								$this->_request->getPost('team_'.($count+1)),
								$this->_request->getPost('user_'.($count+1)));
						
					
					
					}
				}
	
	
				$this->_redirect('/admin/cup-ko/');
			}else{
	
			}
				
	
	
		}
	
	}
	
	
	public function cupKoTeamVsAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_cup_ko = new Model_CupKo();
		$cups = $model_cup_ko->getAllCups('desc');
		
		$this->view->cups = $cups;
		
	
	}
	
	public function cupKoTeamVsModifyAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
	
			$model_cup_ko = new Model_CupKo();
			$cup = $model_cup_ko->getCupKoById($cup_id);

			$model_cup_ko_team = new Model_CupKoTeam();
			$teams = $model_cup_ko_team->getTeamsByCupKoId($cup_id);
	
		
			
			$model_cup_ko_game = new Model_CupKoGame();
			
			$ko_all_teams = $model_cup_ko_game->getGamesByCupId($cup_id);
			$ko_all_games = $model_cup_ko_game->getAllGamesByCupId($cup_id);
			$ko_teams = "";
			foreach ($ko_all_teams as $ko_team){
				if(isset($ko_teams[$ko_team['node_id']])){
					
				}else{
				$ko_teams[$ko_team['node_id']]['home_team_name'] = $ko_team['home_team_name'];
				$ko_teams[$ko_team['node_id']]['away_team_name'] = $ko_team['away_team_name'];
				}
			}
			
			
			$all_active_user_ids = "";
			$all_user_names = "";
			$all_cup_team_ids = "";
			$all_cup_team_names ="";
				
			$this->view->cup = $cup;
			$this->view->teams = $ko_teams;
			
			foreach($teams as $team){
				$all_active_user_ids .=''.$team['team_id'] .',';
	
			}
			foreach($teams as $team){
				$all_user_names .='"'.$team['team_name'] .'",';
	
			}
			
			foreach($ko_teams as $team){
				$all_cup_team_ids .=''.$team['team_id'] .',';
					
			}
			foreach($ko_teams as $team){
				$all_cup_team_names .='"'.$team['team_name'] .'",';
					
			}
				
			$all_active_user_ids = substr($all_active_user_ids,0,-1);
			$all_user_names = substr($all_user_names,0,-1);
			$all_cup_team_ids = substr($all_cup_team_ids,0,-1);
			$all_cup_team_names = substr($all_cup_team_names,0,-1);

			$this->view->all_team_ids = $all_active_user_ids;
			$this->view->all_team_names = $all_user_names;
			$this->view->all_cup_team_ids = $all_cup_team_ids;
			$this->view->all_cup_team_names = $all_cup_team_names;
			$this->view->all_games = $ko_all_games;
	      
		}
	
	}
	
	
	public function saveCupKoTeamVsAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
			if($this->_request->isPost() ){
				$model_cup_ko = new Model_CupKo();
				$model_cup_ko_game = new Model_CupKoGame();
				$cup = $model_cup_ko->getCupKoById($cup_id);
				
				$type = $cup->type;
				$node = 1;
				$team_count = $cup->team_count;
				while( $team_count!=1){
 					for($i=0;$i<floor($team_count/2);$i++){
 						$model_cup_ko_game->updateGame($cup_id,$node,
 								                       $this->_request->getPost('away_team_' . $node),
 								                        $this->_request->getPost('home_team_' . $node),
 								                       $type);	 										
						$node++;							
					}				
					$team_count = ceil($team_count/2);					
				}			
			}else{
				
			}
			
		}
	 $this->_redirect('/admin/cup-ko-team-vs/');
	
	}
	
	
	public function cupKoScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup_id');
	
		$model_cup_ko_team = new Model_CupKoTeam();
		$model_cup_ko= new Model_CupKo();
		if ($cup_id==0){
			$cup_id = $model_cup_ko->getFirstCupId()->id;
	
		}
		$cups = $model_cup_ko->getAllCups();
	
		if($cup_id!=0){
							
			$model_cup_ko_game = new Model_CupKoGame();
			$cup = $model_cup_ko->getCupKoById($cup_id);
			
			$round = 1;
			$node = 1;
			$team_count = $cup->team_count;
			while( $team_count!=1){
				for($i=0;$i<floor($team_count/2);$i++){
					$finished_games[$round] =  $model_cup_ko_game->getFinishedGamesByCupId($cup_id,$round);
					$to_confirm_games[$round] = $model_cup_ko_game->getToConfirmGamesByCupId($cup_id,$round);
					$to_start_games[$round] = $model_cup_ko_game->getToStartGamesByCupId($cup_id,$round);
			
					$node++;
				}
				$team_count = ceil($team_count/2);
				$round++;
			}
					
				
				
			$this->view->finished_games = $finished_games;
			$this->view->to_confirm_games = $to_confirm_games;
			$this->view->to_start_games = $to_start_games;
			$this->view->cups = $cups;
			$this->view->actuel_cup_id = $cup_id;
			$this->view->actuel_cup_name = $cup->name;
		}else{
	
		}
	
	
	}
	
	public function cupKoInputScoreAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$game_id = (int)$this->_getParam('game-id');
	
		if($game_id!=0){
	
			if($this->_request->isPost() ){
				$model_ko_game = new Model_CupKoGame();
				$model_ko_game->updateGameScoreByAdminUser($game_id,
						$this->_request->getPost('away_team_score'),
						$this->_request->getPost('home_team_score')     );
				$this->_redirect('/admin/cup-ko-score/cup_id/'.$model_ko_game->getGameById($game_id)->cup_id);
			}else{
	
			}
	
	
	
		}
	}
	
	public function cupKoCloseAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup-id');
		if($cup_id!=0){
			$model_cup_ko = new Model_CupKo();
			$cup = $model_cup_ko->closeCupById($cup_id);
			$this->_redirect('/admin/cup-ko/');
	
		}
	
	}
	
	
	public function cupKoSummaryAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$cup_id = (int)$this->_getParam('cup_id');
	
		$model_cup_ko_team = new Model_CupKoTeam();
		$model_cup_ko= new Model_CupKo();
		if ($cup_id==0){
			$cup_id = $model_cup_ko->getFirstCupId()->id;
	
		}
		$cups = $model_cup_ko->getAllCups();
	
		if($cup_id!=0){
	
			$model_cup_ko_game = new Model_CupKoGame();
			$cup = $model_cup_ko->getCupKoById($cup_id);
				
		   $games_org = $model_cup_ko_game->getAllGamesByCupId($cup_id);
		   $games = array();
		   $round = 1;
		   foreach($games_org as $game){
		   	   $game['away_team_name'] = empty($game['away_team_id'])?'':$model_cup_ko_team->getCupTeamInfoByCupIdAndTeamId($cup_id, $game['away_team_id'])->team_name;
		   	   $game['home_team_name'] = empty($game['home_team_id'])?'':$model_cup_ko_team->getCupTeamInfoByCupIdAndTeamId($cup_id, $game['home_team_id'])->team_name;
		   	   $games[$game['round']][] = $game;	
		   	   $round = max($game['round'],$round);	   	   
		   }
		  
		   
			$this->view->cups = $cups;
			$this->view->detail_teams = $details;
			$this->view->actuel_cup_name = $cup->name;
			$this->view->actuel_cup_id = $cup_id;
			$this->view->games = $games;
			$this->view->round  = $round;
			$this->view->cup = $cup;
		}
	}
	
	////////////////////////////////////////////user part
	
	public function userAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$model_user = new Model_User();
		$users = $model_user->getAllUsers('desc');
		
		$this->view->users = $users;
		
	}
	
	public function newUserAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
		
		$form = new Form_CreateUser();		
		$form->setAction($this->_request->getRequestUri());
		
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
	
			if ($form->isValid( $this->_request->getPost() )) {
	
				$model_user = new Model_User();
				$model_user->createNewUser($this->_request->getPost('username'),$this->_request->getPost('password'));
	            
	
				$this->_redirect('/admin/user/');
			}
	
		}
	
		$this->view->form = $form;
		
	}
	
	
	public function disactiveUserAction(){
		
		$user_id = (int)$this->_getParam('user-id');
		
		$model_user = new Model_User();
		$model_user->disactiveUserById($user_id);
		
		$this->_redirect('/admin/user/');
		
	}
	
	public function activeUserAction(){
	
		$user_id = (int)$this->_getParam('user-id');
	
		$model_user = new Model_User();
		$model_user->activeUserById($user_id);
	
		$this->_redirect('/admin/user/');
	
	}
	public function updateUserPasswordAction(){
		$this->_helper->actionStack('reduit', 'header');
		$this->_helper->actionStack('admin-options', 'left-menu');
	
		$user_id = (int)$this->_getParam('user-id');
		if($user_id!=0){
			$model_user = new Model_User();
			$user = $model_user->getUserById($user_id);
							
		}else{
			$this->_redirect('/admin/user/');
		}
		
		$form = new Form_CreateUser();		
		$form->setAction($this->_request->getRequestUri());
		
		$form->username->disabled = 'disabled';
		$form->username->setValue($user->username);
		$form->password->setLabel('新密码');
		$form->submit->setLabel('修改');
		
		if($this->_request->isPost()  && $this->_request->getPost( 'cible' ) == 'create'){
	
			if ($form->isValidPartial( $this->_request->getPost() )) {
	
				$model_user = new Model_User();
				$model_user->updateUserPassword($user_id,$this->_request->getPost('password'));
	            
	
				$this->_redirect('/admin/user/');
			}
	
		}
	
		$this->view->form = $form;
	}
	
	protected function _manageFormLogin() {
		$form = new Form_AdminLogin();
		$form->setAction( $this->_request->getRequestUri() );
		
		if ($this->_request->isPost() && $this->_request->getPost( 'cible' ) == 'login') {

			if ($form->isValid( $this->_request->getPost() )) {
				
				$authAdapter = $form->username->getValidator( 'LoginPasswordOk' )->getAuthAdapter();
				
				// récupère les informations du compte pour les mettre dans le
				// cookie :
				$data = $authAdapter->getResultRowObject ( null, 				// whitelist
					array (
							'password'
					) )				// blacklist
					;
				
				$formValues = $form->getValues();
				if ($formValues ['remember_me']) {
					$sessionLifetime = 121536000; // 4 ans environ
					                              
					// reglage du lifetime dans le cookie :
					Zend_Session::rememberMe ( $sessionLifetime );
					
					// reglage du lifetime dans les données de session
					Zend_Session::getSaveHandler()->setLifetime( $sessionLifetime, true );
				} else {
					// reglage du lifetime dans le cookie :
					Zend_Session::forgetMe(); // cookie de session
					                          
					// reglage du lifetime dans les données de session
					Zend_Session::getSaveHandler()->setLifetime( 86400, true ); // 24 heures
				}
				
				// écriture dans les données de session :
				$auth = Zend_Auth::getInstance();
				$auth->setStorage(new Zend_Auth_Storage_Session( 'Admin'));
				$auth->getStorage()->write( $data );
				
	
				
			
				// redirection :
				$redirectNamespace = new Zend_Session_Namespace( 'redirect' );
				$redirectUrl = $redirectNamespace->redirectUrl;
				
				if ($redirectUrl) {
					$redirectNamespace->redirectUrl = '/'; // on ne fait la
					                                       // redirection qu'une fois
					$this->_redirect( $redirectUrl );
				} else {
					$this->_redirect( '/admin/league' );
				}
			} else {
				
				// //fin de validation du compte mci
				$message = 'erreur dans le login ou mot de passe';
				//$this->_helper->messageNow( $message );
			}
		}
		return $form;
	}
	
	public function getAvailableUserIdsByLeagueIdAction(){
		if ($this->_request->isPost() ) {
			$model_league_team = new Model_LeagueTeam();
			$users = $model_league_team->getUsersByLeagueId($this->_request->getPost( 'league_id' ));
			
			$layout = Zend_Controller_Action_HelperBroker :: getStaticHelper('layout');
			$layout->disableLayout();
			
			$ids = '';
			foreach($users as $user){
				$ids .= $user['id'] .'-' ;				
			}
			print_r(substr($ids,0,-1));
			die();
			
		}else{
			
		}
	}
	
	private function sortCupGames($games,$team_count,$model_cup_team,$cup_id,$group_name){
		$detail_teams ="";
		/* for the sorting */
		$teams = array();
		$teams_diff = array();
		$teams_got = array();
		$teams_ids = array();
		
		for($nb=1;$nb<$team_count+1;$nb++){
			$detail['team_name'] = $model_cup_team->getCupTeamInfoByCupIdAndGroupNameAndTeamId($cup_id,$group_name,$nb)->team_name;
			$detail['logo'] = $model_cup_team->getCupTeamInfoByCupIdAndGroupNameAndTeamId($cup_id,$group_name,$nb)->logo;				
			$detail['match'] = 0;
			$detail['score'] = 0;
			$detail['win'] = 0;
			$detail['tie'] = 0;
			$detail['lose'] = 0;
			$detail['got'] = 0;
			$detail['lost'] = 0;
			$detail['diff'] = 0;
			$detail_teams[$nb] = $detail;
			$teams[$nb] = 0;
			$teams_diff[$nb] = 0;
			$teams_got[$nb] = 0;
			$teams_ids[$nb] = $nb;
		}
		
		foreach($games as $game){
			if($game->home_team_confirm=='yes' && $game->away_team_confirm=='yes'){
				$detail_teams[$game->home_team_id]['match']++;
				$detail_teams[$game->away_team_id]['match']++;
				if($game->home_team_score>$game->away_team_score){
					$detail_teams[$game->home_team_id]['score'] += 3;
					$detail_teams[$game->home_team_id]['win']++;
					$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
					$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
					$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
						
					$detail_teams[$game->away_team_id]['lose']++;
					$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
					$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
					$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
						
					$teams[$game->home_team_id] +=3;
					$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
					$teams_got[$game->home_team_id] += $game->home_team_score;
					$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
					$teams_got[$game->away_team_id] += $game->away_team_score;
		
				}else if($game->home_team_score==$game->away_team_score){
					$detail_teams[$game->home_team_id]['score'] ++;
					$detail_teams[$game->home_team_id]['tie']++;
					$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
					$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
					$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
		
					$detail_teams[$game->away_team_id]['score'] ++;
					$detail_teams[$game->away_team_id]['tie']++;
					$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
					$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
					$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
		
					$teams[$game->home_team_id] ++;
					$teams[$game->away_team_id] ++;
					$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
					$teams_got[$game->home_team_id] += $game->home_team_score;
					$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
					$teams_got[$game->away_team_id] += $game->away_team_score;
		
				}else if($game->home_team_score<$game->away_team_score){
					$detail_teams[$game->home_team_id]['lose']++;
					$detail_teams[$game->home_team_id]['got'] +=$game->home_team_score;
					$detail_teams[$game->home_team_id]['lost'] +=$game->away_team_score;
					$detail_teams[$game->home_team_id]['diff'] += $game->home_team_score - $game->away_team_score;
						
					$detail_teams[$game->away_team_id]['score'] += 3;
					$detail_teams[$game->away_team_id]['win']++;
					$detail_teams[$game->away_team_id]['got'] +=$game->away_team_score;
					$detail_teams[$game->away_team_id]['lost'] +=$game->home_team_score;
					$detail_teams[$game->away_team_id]['diff'] += $game->away_team_score - $game->home_team_score;
						
					$teams[$game->away_team_id] +=3;
					$teams_diff[$game->home_team_id] += $game->home_team_score - $game->away_team_score;
					$teams_got[$game->home_team_id] += $game->home_team_score;
					$teams_diff[$game->away_team_id] += $game->away_team_score - $game->home_team_score;
					$teams_got[$game->away_team_id] += $game->away_team_score;
				}
			}
				
		}
		

		array_multisort($teams,SORT_DESC,SORT_NUMERIC ,$teams_diff,SORT_DESC,SORT_NUMERIC ,$teams_got,SORT_DESC,SORT_NUMERIC ,$teams_ids );
		
		
		foreach ($teams_ids as $id ){
			$detail_teams_dup[] = $detail_teams[$id];
		}
		
		return $detail_teams_dup;
	}
}
    
